import type { FC } from 'react';
import { useMemo, memo } from 'react';
import { Stage, Layer, Group } from 'react-konva';
import { getGrids } from './helper';
import { GridType } from '../types';
import Grid, { type GridProps } from './grid';
import Rule from './rule';

type GridsProps = Omit<GridProps, 'col' | 'row'>;

const Grids: FC<GridsProps> = (props) => {
  const { rows, cols, cellSize } = props;

  const grids = useMemo(() => {
    return getGrids(rows, cols);
  }, [rows, cols]);

  const contentWidth = cols * cellSize;
  const contentHeight = rows * cellSize;

  const wrapperWidth = contentWidth + 2 * cellSize;
  const wrapperHeight = contentHeight + 2 * cellSize;

  const renderGrid = (grid: GridType) => {
    const { row, column } = grid;
    const id = [row, column].join('-');
    return (
      <Grid
        key={id}
        {...props}
        row={row}
        col={column}
      />
    );
  }

  return (
    <Stage
      name='grids'
      width={wrapperWidth}
      height={wrapperHeight}
    >
      <Layer>
        <Group x={cellSize} y={cellSize}>
          {grids.map(renderGrid)}
        </Group>
        <Rule
          type="vertical"
          size={cellSize}
          count={rows}
        />
        <Rule
          type="horizontal"
          size={cellSize}
          count={cols}
        />
      </Layer>
    </Stage>
  );
};

export default memo(Grids);